package com.iedu.demo.lgq.controller;

import com.iedu.demo.lgq.entity.*;
import com.iedu.demo.lgq.mapper.OrderItemMapper;
import com.iedu.demo.lgq.mapper.OrderMapper;
import com.iedu.demo.lgq.service.OrderService;
import com.iedu.demo.lgq.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Date;
@RestController
@RequestMapping("/orders")
@CrossOrigin(origins = "http://localhost:8080")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;


    /**
     * 创建订单
     *
     * @param userName     用户ID
     * @param items        订单项列表
     * @param payment      支付金额
     * @param paymentType  支付方式
     * @param postFee      邮费
     * @param buyerMessage 买家留言
     * @return 创建的订单
     */
    @PostMapping("/create")
    @Operation(summary = "创建订单")
    public TbOrder createOrder(@RequestParam String userName,
                               @RequestBody List<TbOrderItem> items,
                               @RequestParam String payment,
                               @RequestParam Integer paymentType,
                               @RequestParam String postFee,
                               @RequestParam String buyerMessage,
                               @RequestParam long addressId
    ) {
        // 获取用户信息
       /*TbUser user = userService.findById(userName);  // 通过 userName 查询用户
        // 如果用户不存在，则返回失败
        if (user == null) {
            return null;  // 或者抛出一个异常，返回用户不存在的错误
        }*/

        // 获取用户的收货地址
        TbUserAddress userAddress = userService.getUserAddressById(addressId);

        // 如果地址不存在，则返回失败
        if (userAddress == null) {
            return null;  // 或者抛出一个异常，返回地址不存在的错误
        }

        // 调用 Service 层的 createOrder 方法，传递必要的参数
        return orderService.createOrder(userName, items, payment, paymentType, postFee, buyerMessage, userAddress);
    }


    // 分页查询订单，支持模糊查询
    @GetMapping("/list")
    @Operation(summary = "分页查询订单，支持模糊查询")
    public List<TbOrder> getOrders(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false)Integer userId,
            @RequestParam(required = false) Integer orderId
    ) {
        return orderService.getOrders(page, pageSize, status, userId, orderId);

    }

    // 根据订单ID查询订单详情
    @Operation(summary = "根据订单ID查询订单详情")
    @PostMapping("/{orderId}")
    public ResponseEntity<TbOrder> getOrderById(@PathVariable Integer orderId) {
        TbOrder order = orderService.getOrderById(orderId);
        if (order == null) {
            return ResponseEntity.notFound().build(); // 如果没有找到订单，返回 404
        }
        return ResponseEntity.ok(order); // 正常返回订单数据
    }


    // 更新订单状态
    @PutMapping("/status/{orderId}")
    @Operation(summary = "更新订单状态")
    public boolean updateOrderStatus(@PathVariable Integer orderId, @RequestParam Integer status) {
        return orderService.updateOrderStatus(orderId, status);
    }

    //用户申请退款
    @PostMapping("/applyRefund")
    @Operation(summary = "用户申请退款")
    public String applyRefund(@RequestParam Integer orderId, @RequestParam String refundReason) {
        // 默认 refundStatus 为 1（已申请退款）
        Integer refundStatus = 1;
        return orderService.applyRefund(orderId, refundStatus, refundReason);
    }
    // 商家处理退款
    @PostMapping("/order/refund/{orderId}")
    @Operation(summary = "商家处理退款")
    public String processRefund(@PathVariable("orderId") Integer orderId) {
        // 商家处理退款时，不需要 refundStatus 和 refundReason
        return orderService.processRefund(orderId);
    }

    // 更新退款状态
    @PutMapping("/refund/{orderId}")
    @Operation(summary = "更新退款状态")
    public boolean updateRefundStatus(@PathVariable Integer orderId, @RequestParam Integer refundStatus, @RequestParam String refundReason) {
        return orderService.updateRefundStatus(orderId, refundStatus, refundReason);
    }
    //用户获取订单退款状态

    @GetMapping("/refundStatus")
    @Operation(summary = "获取退款状态")
    public String getRefundStatus(@RequestParam Integer orderId) {
        return orderService.getRefundStatus(orderId);
    }

    // 批量删除订单
    @DeleteMapping("/delete")
    @Operation(summary = "批量删除订单")
    public void deleteOrders(@RequestBody List<String> orderIds) {
        orderService.deleteOrders(orderIds);

    }

    //商家发货
    @PostMapping("/order/ship/{orderId}")
    @Operation(summary = "商家发货")
    public String shipOrder(@PathVariable("orderId") Integer orderId) {

        return orderService.shipOrder(orderId);
    }


    //获取所有快递公司
 @GetMapping("/delivery-companies")
 @Operation(summary = "获取所有快递公司")
 public List<Kuaidi100Delivery> getAllDeliveryCompanies() {
     return orderService.getAllDeliveryCompanies();
 }

    // 商家选择快递公司
    @PostMapping("/select-delivery")
    @Operation(summary = "商家选择快递公司")
    public String selectDeliveryCompany(
            @RequestParam Integer orderId,
            @RequestParam long deliveryId,
            @RequestParam String trackingNumber
    ) {
        return orderService.selectDeliveryCompany(orderId, deliveryId,trackingNumber);
    }


}

